package com.coin900.coin.cmd.token;

import com.coin900.coin.cmd.ACmd;
import com.coin900.coin.cmd.CmdSign;
import com.coin900.coin.code.CmdCode;
import com.coin900.coin.persist.coin.CoinTokenVO;
import com.coin900.coin.persist.fu.FuUserVO;
import com.coin900.coin.service.coin.ICoinTokenService;
import com.google.gson.Gson;
import com.value.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 添加或修改代币
 *
 * @author shui
 * @create 2018-01-15
 **/
@Controller
public class CoinTokenPutCmd extends ACmd {
    @Override
    public CmdSign execute(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        FuUserVO user = super.getUser(sign);
        String source = sign.getSource();
        CoinTokenVO coinTokenVO = new Gson().fromJson(source, CoinTokenVO.class);
        Long coinId = coinTokenVO.getCoinId();
        if (coinId == null) {
            coinTokenVO.setCreatedInfor(user);
            this.tokenService.insertCoinToken(coinTokenVO);
        } else {
            Map<String, Object> params = new HashMap<>();
            params.put("coinId", coinId);
            params.put("dataStatus", 1);
            List<CoinTokenVO> coinTokenVOS = this.tokenService.loadCoinToken(params);
            if (coinTokenVOS.isEmpty()) {
                throw new BusinessException("分类不存在");
            }
            coinTokenVO.setModifiedInfor(user);
            this.tokenService.updateCoinToken(coinTokenVO);
        }
        return respSign;
    }

    @Autowired
    private ICoinTokenService tokenService;

    @Override
    public String getCmdCode() {
        return CmdCode.COIN_TOKEN_PUT;
    }
}
